import { defineStore } from 'pinia'
import type { CommentDTO, CommentVO } from '@/request/api/comment'
import { io, Socket } from 'socket.io-client'

// 非持久化
export const useSocketStore = defineStore('socket', () => {
  let commentSocket: Socket | null = null

  const initCommentSocket = (onCommentReceived: (comment: CommentVO) => void) => {
    if (!commentSocket) {
      commentSocket = io('http://localhost:9092/comment', {
        transports: ['websocket'], // 指定传输方式，如WebSocket
        autoConnect: true, // 是否自动连接
        reconnection: true, // 是否自动重新连接
        reconnectionAttempts: 3, // 重新连接尝试次数
        reconnectionDelay: 100 // 重新连接延迟时间（毫秒）
        // query: { token: 'your-token' } // 自定义查询参数
        // 其他可选参数...
      })
      commentSocket.on('connect', () => {
        console.log('Connected to Socket.IO server')
      })

      commentSocket.on('disconnect', () => {
        console.log('Disconnected from Socket.IO server')
      })

      commentSocket.on('commentMessage', (data: CommentVO) => {
        onCommentReceived(data)
      })
    }
  }
  // 发送消息
  const sendCommentSocket = (message: CommentDTO) => {
    if (commentSocket) {
      commentSocket.emit('commentSocket', message)
    }
  }

  const connectCommentSocket = () => {
    if (commentSocket) {
      commentSocket.connect()
    }
  }

  return {
    initCommentSocket,
    sendCommentSocket,
    connectCommentSocket
  }
})
